import React, { FC, useEffect, useState } from 'react';
import { useForm, useField } from '@formily/react';
import { TextWidget } from '@inbiz/react';
import { Button, Form, Select, message, Spin, Modal as ModalAntd } from 'antd';
import { useQueryFields } from '@inbiz/hooks';
import './style.less';
const { Option } = Select;

const prefixCls = 'inbiz-Cascader-designer-configModal';
export type IValue = {
  currentIdField: string;
  parentIdField: string;
  labelField: string;
};
interface IProps {
  value: IValue;
  update?: string;
  onChange: (v: IValue) => void;
}

type TFormItem = {
  name: string;
};
interface ILocale {
  modalTitle: string;
  title: string;
  requiredmessage: string;
  formitem: {
    currentidfield: TFormItem;
    currentlabelfield: TFormItem;
    parentidfield: TFormItem;
  };
}

const ConfigModal: FC<IProps> = ({ value, update, onChange }) => {
  const globalForm = useForm();
  const [form] = Form.useForm();
  const takeMessage = useField().takeMessage() as ILocale;
  const [visible, setVisible] = useState(false);

  const FormOtions = [
    {
      label: takeMessage.formitem.currentidfield.name || '当前节点ID属性',
      value: 'currentIdField',
    },
    {
      label: takeMessage.formitem.currentlabelfield.name || '当前节点Text属性',
      value: 'labelField',
    },
    {
      label: takeMessage.formitem.parentidfield.name || '父节点ID属性',
      value: 'parentIdField',
    },
  ];

  const [fields, loading] = useQueryFields(
    {
      key: globalForm.fields?.['form.senior.soure.x-component-props.sourceModel']?.value,
      appId: globalForm.appInfo.appId,
    },
    [update],
  );

  const showModal = () => {
    if (!globalForm.fields?.['form.senior.soure.x-component-props.sourceModel']?.value) {
      message.warn('请先选择查询数据源');
      return;
    }
    setVisible(true);
  };

  const onOk = async () => {
    const formValue = await form.validateFields();
    onChange(formValue);
    setVisible(false);
  };

  const onCancel = () => {
    form.resetFields();
    setVisible(false);
  };

  useEffect(() => {
    if (visible) {
      const keys = Object.keys(value ?? {});
      keys.forEach((ele) => {
        const currentValue = value?.[ele]?.split('$')[1];
        if (fields.every((child) => child.value !== currentValue)) {
          value[ele] = null;
        }
      });
      form.setFieldsValue(value);
    }
  }, [visible]);

  return (
    <>
      <Button type="primary" onClick={showModal}>
        {takeMessage.modaltitle || '配置'}
      </Button>
      <ModalAntd
        className={prefixCls}
        title={takeMessage.modaltitle || '配置'}
        visible={visible}
        width={450}
        bodyStyle={{ padding: '32px 64px' }}
        okText={<TextWidget>global.sure</TextWidget>}
        cancelText={<TextWidget>global.cancel</TextWidget>}
        onOk={onOk}
        onCancel={onCancel}
        confirmLoading={loading}
        destroyOnClose
      >
        <Spin spinning={loading}>
          <Form form={form} labelCol={{ span: 11 }} wrapperCol={{ span: 13 }} labelAlign="left">
            {FormOtions.map((item) => (
              <Form.Item
                key={item.value}
                name={item.value}
                label={item.label}
                rules={[{ required: true, message: takeMessage.requiredmessage || '该字段必填' }]}
              >
                <Select
                showSearch
                filterOption={(input, option) =>
                  (option?.value ?.toString()?? '').toLowerCase().includes(input.toLowerCase())
                }
                 allowClear>
                  {fields.map((option) => (
                    <Option
                      key={option.value}
                      value={`${
                        option.origin_FieldName?.split('$')?.[1]
                          ? option.origin_FieldName?.split('$')?.[1]
                          : ''
                      }$${option.value}`}
                    >
                      {option.value}
                    </Option>
                  ))}
                </Select>
              </Form.Item>
            ))}
          </Form>
        </Spin>
      </ModalAntd>
    </>
  );
};

export default ConfigModal;
